package com.glink.manage.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.glink.common.exception.GeneralSimpleException;
import com.glink.common.util.BaseCommonUtils;
import com.glink.manage.common.Constants;
import com.glink.manage.common.FileTools;
import com.glink.manage.domain.AppVersionManageBean;
import com.glink.manage.domain.AttachmentImageBean;
import com.glink.manage.dto.upload.*;
import com.glink.manage.ftp.FTPUtils;
import com.glink.manage.mapper.AttachmentImageMapper;
import com.glink.manage.service.AppVersionManageService;
import com.glink.manage.service.AttachmentService;
import com.glink.manage.vo.upload.AttachmentAppVO;
import com.glink.manage.vo.upload.AttachmentImageUploadVO;
import com.glink.manage.vo.upload.AttachmentImageVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by IntelliJ IDEA.
 *
 * @Author : qiushaoshan
 * @create 2024/7/5 13:03
 */
@Service
@Slf4j
public class AttachmentServiceImpl extends ServiceImpl<AttachmentImageMapper, AttachmentImageBean> implements AttachmentService {

    private static final String GET_FILE_PATTERN = "file:";

    private static final String IMAGE = "image";
    private static final String ATTACHMENT = "Attachment";

    private static final String APP = "app";

    @Value("${spring.resources.static_url_prefix:/API/Manage/static/}")
    private String staticUrlPrefix;

    @Value("${app.name:智慧工地.apk}")
    private String APP_NAME;

    @Value("${barrier_gate.callback.prefix.url:http://192.168.1.31}")
    private String callbackPrefixUrl;

    @Value("${spring.resources.static-locations:file:/home/manage/data}")
    private String PROJECT_BASE_DIR;

    private String PROJECT_BASE_DIR_IMAGE;

    private String PROJECT_BASE_DIR_ATTACHMENT;

    private String PROJECT_BASE_DIR_APP;

    @Autowired
    private AppVersionManageService appVersionManageService;

    @Autowired
    private FTPUtils ftpUtils;

    @PostConstruct
    public void init() {
        if (PROJECT_BASE_DIR.startsWith(GET_FILE_PATTERN)) {
            PROJECT_BASE_DIR = PROJECT_BASE_DIR.replaceFirst(GET_FILE_PATTERN, "");
        }

        if (PROJECT_BASE_DIR.endsWith("/")) {
            PROJECT_BASE_DIR_IMAGE = PROJECT_BASE_DIR + IMAGE;
            PROJECT_BASE_DIR_ATTACHMENT = PROJECT_BASE_DIR + ATTACHMENT;
            PROJECT_BASE_DIR_APP = PROJECT_BASE_DIR + APP;
        } else {
            PROJECT_BASE_DIR_IMAGE = (PROJECT_BASE_DIR + "/" + IMAGE);
            PROJECT_BASE_DIR_ATTACHMENT = (PROJECT_BASE_DIR + "/" + ATTACHMENT);
            PROJECT_BASE_DIR_APP = (PROJECT_BASE_DIR + "/" + APP);
        }
    }

    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public List<String> onlyUploadStaticImages(UploadImageListDTO dto, String userId) throws GeneralSimpleException {
        List<String> ret = new ArrayList<>();
        try {
            if (!CollectionUtils.isEmpty(dto.getFileList())) {
                //获取当前月份
                DateTime dateTime = DateUtil.date();
                String path = PROJECT_BASE_DIR_IMAGE + File.separator;

                if (StringUtils.isNotBlank(dto.getOrgId())) {
                    path += dto.getOrgId() + File.separator;
                }

                path += dateTime.year() + File.separator +
                        (dateTime.month() + 1) + File.separator +
                        dateTime.dayOfMonth() + File.separator;

                List<AttachmentImageBean> imageBeanList = Lists.newArrayList();
                for (MultipartFile img : dto.getFileList()) {
                    if (Objects.nonNull(img)) {
                        String originalFilename = img.getOriginalFilename();
                        String imgId = BaseCommonUtils.generateUUID();
                        log.info("开始上传 文件 {} ", originalFilename);
                        if (FileTools.uploadImage(img, path, imgId)) {
                            String newFileName = FileTools.getNewFileName(imgId);
                            ret.add(newFileName);

                            AttachmentImageBean imageBean = new AttachmentImageBean();
                            imageBean.setId(newFileName);
                            imageBean.setPointer(path);
                            imageBean.setName(originalFilename);
                            imageBean.setModelType(dto.getModelType());
                            imageBean.setOrgId(dto.getOrgId());
                            imageBean.setDataSource("2");
                            imageBeanList.add(imageBean);
                        } else {
                            log.error("请注意文件{}上传失败", originalFilename);
                            throw new GeneralSimpleException("200014");
                        }
                    }
                }

                if(CollectionUtils.isNotEmpty(imageBeanList)){
                    boolean status = this.saveBatch(imageBeanList);
                    if(status){
                        return ret;
                    }
                }
            }
        } catch (Exception e) {
            throw new GeneralSimpleException("200014");
        }

        return ret;
    }

    /**
     * 上传文件
     * @param file 文件信息
     * @param orgId 组织机构
     * @param modelType 模型类型
     * @return 图片信息
     * @throws GeneralSimpleException 异常
     */
    @Override
    public AttachmentImageBean uploadImage(File file, String orgId, String modelType) throws GeneralSimpleException {
        AttachmentImageBean imageBean = null;
        if (Objects.nonNull(file)) {

            //获取当前月份
            DateTime dateTime = DateUtil.date();
            String path = PROJECT_BASE_DIR_IMAGE + File.separator;

            if (StringUtils.isNotBlank(orgId)) {
                path += orgId + File.separator;
            }

            path += dateTime.year() + File.separator +
                    (dateTime.month() + 1) + File.separator +
                    dateTime.dayOfMonth() + File.separator;
            
            String originalFilename = file.getName();
            String imgId = BaseCommonUtils.generateUUID();
            log.info("开始上传 文件 {} ", originalFilename);
            if (FileTools.uploadImage(file, path, imgId)) {
                String newFileName = FileTools.getNewFileName(imgId);
                imageBean = new AttachmentImageBean();
                imageBean.setId(newFileName);
                imageBean.setPointer(path);
                imageBean.setName(originalFilename);
                imageBean.setModelType(modelType);
                imageBean.setOrgId(orgId);
                imageBean.setDataSource("2");
            }
        }
        
        return imageBean;
    }

    @Override
    public AttachmentImageBean uploadImage(MultipartFile file, String orgId, String modelType) throws GeneralSimpleException {
        AttachmentImageBean imageBean = null;
        if (Objects.nonNull(file)) {

            //获取当前月份
            DateTime dateTime = DateUtil.date();
            String path = PROJECT_BASE_DIR_IMAGE + File.separator;

            if (StringUtils.isNotBlank(orgId)) {
                path += orgId + File.separator;
            }

            path += dateTime.year() + File.separator +
                    (dateTime.month() + 1) + File.separator +
                    dateTime.dayOfMonth() + File.separator;

            String originalFilename = file.getOriginalFilename();
            String imgId = BaseCommonUtils.generateUUID();
            log.info("开始上传 文件 {} ", originalFilename);
            if (FileTools.uploadImage(file, path, imgId)) {
                String newFileName = FileTools.getNewFileName(imgId);
                imageBean = new AttachmentImageBean();
                imageBean.setId(newFileName);
                imageBean.setPointer(path);
                imageBean.setName(originalFilename);
                imageBean.setModelType(modelType);
                imageBean.setOrgId(orgId);
                imageBean.setDataSource("2");
            }
        }

        return imageBean;
    }

    /**
     * 根据图片ID查询图片
     *
     * @param imageId             图片ID
     * @param httpServletResponse HTTP
     */
    @Override
    public void exportStaticFile(String imageId, String type, HttpServletResponse httpServletResponse) {
        String path = "";
        String fileName = "";
        if (StringUtils.isNotBlank(imageId)) {
            AttachmentImageBean imageBean = this.lambdaQuery().eq(AttachmentImageBean::getId, imageId).one();
            if (Objects.nonNull(imageBean)) {
                String pointer = imageBean.getPointer();
                fileName = imageBean.getName();
                if (StringUtils.isNotBlank(pointer)) {
                    path += pointer + File.separator + type + File.separator + imageBean.getId();
                }
            }
        }

        try {
            exportStaticFileFlow(path, fileName, httpServletResponse);
        } catch (Exception ex) {
            log.info("读取图片异常:{}", ex.getMessage());
            httpServletResponse.setStatus(HttpStatus.NOT_FOUND.value());
        }

    }

    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public String onlyUploadStaticImagesOne(UploadImageDTO dto, String userId) throws GeneralSimpleException {
        String ret = "";
        try {
            if (Objects.nonNull(dto.getFile())) {
                MultipartFile img = dto.getFile();
                //获取当前月份
                DateTime dateTime = DateUtil.date();
                String path = PROJECT_BASE_DIR_IMAGE + File.separator;

                if (StringUtils.isNotBlank(dto.getOrgId())) {
                    path += dto.getOrgId() + File.separator;
                }

                path += dateTime.year() + File.separator +
                        (dateTime.month() + 1) + File.separator +
                        dateTime.dayOfMonth() + File.separator;

                String originalFilename = img.getOriginalFilename();
                String imgId = BaseCommonUtils.generateUUID();
                log.info("开始上传 文件 {} ", originalFilename);
                if (FileTools.uploadImage(img, path, imgId)) {
                    ret = FileTools.getNewFileName(imgId);

                    AttachmentImageBean imageBean = new AttachmentImageBean();
                    imageBean.setId(ret);
                    imageBean.setPointer(path);
                    imageBean.setName(originalFilename);
                    imageBean.setModelType(dto.getModelType());
                    imageBean.setOrgId(dto.getOrgId());

                    this.save(imageBean);
                } else {
                    log.error("请注意文件{}上传失败", originalFilename);
                    throw new GeneralSimpleException("200014");
                }

            }
        } catch (Exception e) {
            throw new GeneralSimpleException("200014");
        }

        return ret;
    }

    /**
     * 根据图片ID获取图片信息
     *
     * @param imageId 图片ID
     * @return 图片信息
     */
    @Override
    public byte[] getFileByte(String imageId) {
        AttachmentImageBean attachmentImageBean = this.getById(imageId);
        if (Objects.nonNull(attachmentImageBean) && StringUtils.isNotBlank(attachmentImageBean.getPointer()) && StringUtils.isNotBlank(attachmentImageBean.getName())) {
            String filePath = attachmentImageBean.getPointer() + "/raw/" + attachmentImageBean.getId();
            Path path = Paths.get(filePath);
            try {
                return Files.readAllBytes(path);
            } catch (Exception e) {
                log.error("获取文件流异常", e);
            }
        }

        return null;
    }

    /**
     * 上传附件
     *
     * @param dto    上传附件信息
     * @param userId 用户ID
     * @return 附件ID
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public AttachmentImageUploadVO onlyUploadStaticFile(UploadImageDTO dto, String userId) throws GeneralSimpleException {
        AttachmentImageUploadVO uploadVO = null;
        try {

            if (Objects.nonNull(dto.getFile())) {
                //获取当前月份
                DateTime dateTime = DateUtil.date();
                String path = PROJECT_BASE_DIR_ATTACHMENT + File.separator;

                if (StringUtils.isNotBlank(dto.getOrgId())) {
                    path += dto.getOrgId() + File.separator;
                }

                path += dateTime.year() + File.separator +
                        (dateTime.month() + 1) + File.separator +
                        dateTime.dayOfMonth() + File.separator;

                MultipartFile file = dto.getFile();
                if (Objects.nonNull(file)) {
                    String originalFilename = file.getOriginalFilename();
                    String imgId = BaseCommonUtils.generateUUID();
                    log.info("开始上传 文件 {} ", originalFilename);
                    String newFileName = imgId + "." + FilenameUtils.getExtension(originalFilename);
                    if (FileTools.uploadAttachment(file, path, newFileName)) {

                        AttachmentImageBean imageBean = new AttachmentImageBean();
                        imageBean.setId(newFileName);
                        imageBean.setPointer(path);
                        imageBean.setName(originalFilename);
                        imageBean.setModelType(dto.getModelType());
                        imageBean.setOrgId(dto.getOrgId());
                        imageBean.setDataSource("2");
                        boolean status = this.save(imageBean);
                        if (status) {
                            uploadVO = new AttachmentImageUploadVO();
                            uploadVO.setId(imageBean.getId());
                            uploadVO.setName(imageBean.getName());
                            uploadVO.setModelType(imageBean.getModelType());
                            uploadVO.setOrgId(imageBean.getOrgId());
                        }
                    } else {
                        log.error("请注意文件{}上传失败", originalFilename);
                        throw new GeneralSimpleException("200014");
                    }
                }
            }
        } catch (Exception e) {
            throw new GeneralSimpleException("200014");
        }

        return uploadVO;
    }

    /**
     * 上传APP
     *
     * @param dto 上传APP
     * @return 上传状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean uploadApp(UploadAppDTO dto) throws GeneralSimpleException {

        if (Objects.nonNull(dto.getFile())) {

            List<AppVersionManageBean> versionManageBeanList = appVersionManageService.lambdaQuery().eq(AppVersionManageBean::getVersion, dto.getVersion()).list();
            if (CollectionUtils.isNotEmpty(versionManageBeanList)) {
                AppVersionManageBean versionManageBean = versionManageBeanList.get(0);

                //获取当前月份
                String filePath = PROJECT_BASE_DIR_APP + File.separator + APP_NAME;
                try {
                    MultipartFile multipartFile = dto.getFile();
                    if (Objects.nonNull(multipartFile)) {
                        String originalFilename = multipartFile.getOriginalFilename();
                        log.info("开始上传 文件 {} ", originalFilename);
                        if (FileTools.uploadAPP(multipartFile, filePath)) {
                            versionManageBean.setFileName(APP_NAME);
                            versionManageBean.setFileNameOriginal(originalFilename);
                            return appVersionManageService.updateById(versionManageBean);
                        } else {
                            log.error("请注意文件{}上传失败", originalFilename);
                            throw new GeneralSimpleException("200014");
                        }
                    }
                } catch (Exception e) {
                    throw new GeneralSimpleException("200014");
                }
                
                
            }else{
                //获取当前月份
                String filePath = PROJECT_BASE_DIR_APP + File.separator + APP_NAME;
                try {
                    File file = new File(filePath);
                    if (file.exists()) {
                        AppVersionManageBean versionManageBean = appVersionManageService.lambdaQuery().orderByDesc(AppVersionManageBean::getCreateTime).last(Constants.LAST_SQL).one();
                        String version = getAppFileName(versionManageBean);

                        // 如果文件存在，则进行文件备份
                        String newFilePath = PROJECT_BASE_DIR_APP + File.separator + version;
                        File newFile = new File(newFilePath);
                        Files.copy(file.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
                    }

                    MultipartFile multipartFile = dto.getFile();
                    if (Objects.nonNull(multipartFile)) {
                        String originalFilename = multipartFile.getOriginalFilename();
                        log.info("开始上传 文件 {} ", originalFilename);
                        if (FileTools.uploadAPP(multipartFile, filePath)) {
                            AppVersionManageBean versionManageBean = new AppVersionManageBean();
                            versionManageBean.setObjId(BaseCommonUtils.generateUUID());
                            versionManageBean.setVersion(dto.getVersion());
                            versionManageBean.setFilePath(filePath);
                            versionManageBean.setFileName(APP_NAME);
                            versionManageBean.setFileNameOriginal(originalFilename);
                            return appVersionManageService.save(versionManageBean);
                        } else {
                            log.error("请注意文件{}上传失败", originalFilename);
                            throw new GeneralSimpleException("200014");
                        }
                    }
                } catch (Exception e) {
                    throw new GeneralSimpleException("200014");
                }
            }
        }

        return false;
    }

    /**
     * 获取文件名称
     * @param versionManageBean APP信息
     * @return APP名称
     */
    private String getAppFileName(AppVersionManageBean versionManageBean){
        if(Objects.isNull(versionManageBean)){
            return "";
        }
        return versionManageBean.getObjId() + "_" + versionManageBean.getVersion() + ".apk";
    }
    
    /**
     * 查询APP列表
     *
     * @return app信息
     */
    @Override
    public AttachmentAppVO listByApp() {
        AttachmentAppVO appVO = null;
        AppVersionManageBean versionManageBean = appVersionManageService.findOneOrderByCreateTimeDesc();
        if (Objects.nonNull(versionManageBean)) {
            appVO = new AttachmentAppVO();
            appVO.setObjId(versionManageBean.getObjId());
            appVO.setVersion(versionManageBean.getVersion());
            appVO.setCreateTime(versionManageBean.getCreateTime());
            appVO.setFileName(versionManageBean.getFileName());
            appVO.setFileNameOriginal(versionManageBean.getFileNameOriginal());

            if (StringUtils.isNotBlank(versionManageBean.getFilePath())) {
                String filePath = versionManageBean.getFilePath();
                filePath = filePath.replace(PROJECT_BASE_DIR, "");
                appVO.setStaticFilePath(staticUrlPrefix + filePath);

                appVO.setStaticFilePath(appVO.getStaticFilePath().replaceAll("//", "/"));
            }
        }
        return appVO;
    }

    @Override
    public String findStaticImagePath(String imageId){
        AttachmentImageBean attachmentImageBean = this.getById(imageId);
        if(Objects.nonNull(attachmentImageBean)){
            String filePath = attachmentImageBean.getPointer();
            filePath = callbackPrefixUrl + staticUrlPrefix + filePath.replace(PROJECT_BASE_DIR, "") + "/raw/" + imageId;
            return filePath.replace("//", "/");
        }
        return null;
    }
    
    /**
     * 查询图片ID，校验是否存在
     *
     * @param imageIdList 图片ID
     * @return 图片ID
     */
    @Override
    public Map<String, String> findImageIdByImageIdIn(List<String> imageIdList) {
        List<AttachmentImageBean> attachmentImageBeanList = this.lambdaQuery().in(AttachmentImageBean::getId, imageIdList).list();
        if(CollectionUtils.isNotEmpty(attachmentImageBeanList)){
            return attachmentImageBeanList.stream().collect(Collectors.toMap(AttachmentImageBean::getId, AttachmentImageBean::getName));
        }
        return null;
    }

    /**
     * 下载FTP图片
     *
     * @param dto      文件路径
     * @param response 返回数据
     */
    @Override
    public void downloadPicByFtp(UploadFilePathDTO dto, HttpServletResponse response) {
        downloadPicByFtp(dto.getFilePath(), response);
    }

    @Override
    public void downloadPicByFtp(String path, HttpServletResponse response) {
        OutputStream outputStream = null;
        try {
            byte[] ftpFileByte = ftpUtils.getFtpFileByte(path);
            if (null != ftpFileByte && ftpFileByte.length > 0) {
                // 清空response
                response.reset();
                // 设置response的Header
                response.setCharacterEncoding("UTF-8");
                response.addHeader("content-type", "application/octet-stream;charset=UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(path.substring(path.lastIndexOf("/") + 1), "UTF-8"));
                response.addHeader("Content-Length", String.valueOf(ftpFileByte.length));
                outputStream = response.getOutputStream();
                response.setContentType("application/octet-stream; charset=UTF-8");
                outputStream.write(ftpFileByte);
                outputStream.flush();
            }
        } catch (Exception e) {
            log.error("ftp下载文件失败,文件路径：{}", path, e);
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
    }

    /**
     * 根据图片ID查询图片信息
     *
     * @param idDTO
     */
    @Override
    public AttachmentImageVO findImageById(UploadImageIdDTO idDTO) throws GeneralSimpleException {

        AttachmentImageBean imageBean = this.lambdaQuery().eq(AttachmentImageBean::getId, idDTO.getImageId()).one();
        if (Objects.nonNull(imageBean)) {
            AttachmentImageVO imageVO = new AttachmentImageVO();
            BeanUtil.copyProperties(imageBean, imageVO);
            return imageVO;
        }
        return null;
    }

    public void exportStaticFileFlow(String path, String name, HttpServletResponse response) {
        File f = null;
        OutputStream outputStream = null;
        try {
            f = new File(path);
            byte[] buffer = FileUtil.readBytes(f);
            if (null != buffer && buffer.length > 0) {
                // 清空response
                response.reset();
                // 设置response的Header
                response.setCharacterEncoding("UTF-8");
                response.addHeader("content-type", "application/octet-stream;charset=UTF-8");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "UTF-8"));
                response.addHeader("Content-Length", String.valueOf(buffer.length));
                outputStream = response.getOutputStream();
                response.setContentType("application/octet-stream; charset=UTF-8");
                outputStream.write(buffer);
                outputStream.flush();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(outputStream);
        }
    }

    /**
     * base64转image
     * @param base64Image base64
     * @return 生成状态
     */
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public String decodeBase64ToImage(String base64Image, String objId, String orgId) {
        String fileName = FileTools.getNewFileName(objId);
        String path = PROJECT_BASE_DIR_IMAGE + File.separator + "capture_img" + File.separator + objId + File.separator;
        
        DateTime dateTime = DateUtil.date();
        path += dateTime.year() + File.separator +
                (dateTime.month() + 1) + File.separator +
                dateTime.dayOfMonth() + File.separator + fileName;
        
        boolean status = false;
        byte[] imageBytes = Base64.getDecoder().decode(base64Image);
        FileOutputStream fos = null;
        try {
            
            File file = new File(path);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            fos = new FileOutputStream(path);
            fos.write(imageBytes);
            status = true;
        } catch (IOException e) {
            e.printStackTrace();
            log.error("base64转文件，异常", e);
            status = false;
        } finally {
            if(fos != null){
                try {
                    fos.close();
                } catch (IOException e) {
                    log.error("base64转文件，关流异常", e);
                }
            }
        }
        
        if(status){
            AttachmentImageBean imageBean = new AttachmentImageBean();
            imageBean.setId(fileName);
            imageBean.setPointer(path);
            imageBean.setName(fileName);
            imageBean.setOrgId(orgId);
            imageBean.setDataSource("2");
            status = this.save(imageBean);
        }
        if(status){
            return fileName;
        }else{
            return null;
        }
    }

    /**
     * 删除APP
     *
     * @param dto 删除条件
     * @return 删除状态
     */
    @Override
    @Transactional(value = "transactionManager", propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Boolean delApp(UploadAppDelDTO dto) {

        AppVersionManageBean appVersionManageBean = appVersionManageService.findOneOrderByCreateTimeDesc();
        if(Objects.nonNull(appVersionManageBean) && StringUtils.equals(appVersionManageBean.getObjId(), dto.getAppId())){
            // 删除的APP是最新的一条
            AppVersionManageBean versionManageBean = appVersionManageService.findOneByObjIdNotOrderByCreateTimeDesc(dto.getAppId());
            
            if(StringUtils.isNotBlank(appVersionManageBean.getFilePath())){
                File file = new File(appVersionManageBean.getFilePath());
                if(file.exists()){
                    if(Objects.nonNull(versionManageBean) && StringUtils.isNotBlank(versionManageBean.getFilePath())){
                        // 是否存在历史版本的APP，如果有，责APP使用旧版本的
                        String version = getAppFileName(versionManageBean);
                        String oldFilePath = PROJECT_BASE_DIR_APP + File.separator + version;
                        
                        File oldFile = new File(oldFilePath);
                        if(oldFile.exists()){
                            try (FileInputStream fis = new FileInputStream(oldFilePath); 
                                 FileOutputStream fos = new FileOutputStream(appVersionManageBean.getFilePath());
                                 FileChannel sourceChannel = fis.getChannel();
                                 FileChannel destinationChannel = fos.getChannel()) {
                                sourceChannel.transferTo(0, sourceChannel.size(), destinationChannel);
                                // 重命名成功
                                return appVersionManageService.removeById(dto.getAppId());
                            } catch (IOException e) {
                                e.printStackTrace();
                                log.error("删除APP异常", e);
                            }
                        }
                    }else{
                        boolean delete = file.delete();
                        if(delete){
                            // 删除成功，删除数据
                            return appVersionManageService.removeById(dto.getAppId());
                        }
                    }
                }else{
                    // 文件不存在，删除数据
                    return appVersionManageService.removeById(dto.getAppId());
                }
            }
        }
        return false;
    }
}
